#include <DHT.h>


/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */

#include <Process.h>
#include <FileIO.h>
#include "temperatureHumidityDewpoint.h"


TemperatureHumidityDewpoint thd_inside(6, 0);
TemperatureHumidityDewpoint thd_outside(7, 0);

int RELAIS_ON = LOW;
int RELAIS_OFF = HIGH;
int fan = RELAIS_OFF;
int sample = 0;


// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(8, fan);
  
  Bridge.begin();
}

// the loop function runs over and over again forever
void loop() {
  thd_inside.readSensor();
  thd_outside.readSensor();
  

  String fanStatus = "0";
  
  if (thd_inside.status == "OK" && thd_outside.status == "OK") {
    if (fan == RELAIS_OFF) {
      if (thd_inside.dewpoint > (thd_outside.dewpoint + 2)) {
        fan = RELAIS_ON;
      }
    } else {
      if (thd_inside.dewpoint < (thd_outside.dewpoint + 1)) {
        fan = RELAIS_OFF;
      }    
    }
  } else {
   fan = RELAIS_OFF; 
  }
  
  File forceonFile = FileSystem.open("/opt/acfg/forceon", FILE_READ);
  int force = forceonFile.parseInt();
  if (force == 1) {
    fan = RELAIS_ON;
  }
  
//  fan = RELAIS_ON;
  
  
  if (fan == RELAIS_ON) {
    fanStatus = "100";
  }
  


  Process p;  
  String line = "/root/log.sh ";

  line += sample;
  line += " , ";
  sample++;

  line += thd_inside.status;
  line += ", ";  

  line += thd_outside.status;
  line += ", ";  
  
  line += thd_inside.temperature;
  line += ", ";
  
   line += thd_inside.humidity;
  line += ", ";
  
  line += thd_inside.dewpoint;
  line += ", "; 
  
  line += thd_outside.temperature;
  line += ", ";
  
  line += thd_outside.humidity;
  line += ", ";
  
  line += thd_outside.dewpoint;
  line += ", ";

  line += fanStatus;

  
  p.runShellCommand(line);
  
  // indicate fan on pin 8
  digitalWrite(8, fan); 
  
  // blink once
  digitalWrite(13, HIGH);
  delay(20);
  digitalWrite(13, LOW);
  
  delay(2000);
}
